package util

import (
	"time"
	"strconv"
	"strings"
	log "code.google.com/p/log4go"
	"fmt"
)

/**
	获取当前的时间戳（字符串格式）
 */
func GetCurrentTimeStr() string {
	timestamp := time.Now().Unix()
	tm := time.Unix(timestamp, 0)
	return tm.Format("2006-01-02 15:04:05")
}

/**
	转为String,针对配置类中的各种类型：
 */
func ToString(args ...interface{}) string {
	result := ""
	for _, arg := range args {
		switch val := arg.(type) {
		case int:
			result += strconv.Itoa(val)
		case string:
			result += val
		case int64:
			result += strconv.FormatInt(val, 10)
		case int8,int16,int32,uint8,uint16,uint32,uint64,uint,uintptr:
			result += fmt.Sprintf("%v",val)
		case bool:
			result += strconv.FormatBool(val)
		case float32:
			result += fmt.Sprintf("%v",val)
		case float64:
			result += fmt.Sprintf("%v",val)
		case []string:
			vals := []string(val)
			for i := range vals {
				result += vals[i] + ","
			}
			//去除最后一个逗号
			result = result[0:len(result)-1]
		case []map[string][]string:
			vals := []map[string][]string(val)
			for i := range vals {
				for key,valsrange:=range vals[i]{
					result +=key
					result +="["
					for j := range valsrange {
						result += valsrange[j] + ","
					}
					result +="]"
				}
			}
			result =strings.Replace(result,",]","]",-1)
		}
	}
	return result
}
/**
	将String 类型转为int64
 */
func ToInt64(value string,defaultvalue int64) (v int64){
	nt64, err := strconv.ParseInt(value, 10, 64)
	if err!= nil {
		log.Error(err)
		return defaultvalue
	}
	return nt64
}
/**
	将字符串转化为字符串数组，根据字符串切割
 */
func ToSTringSlice(value string) (v []string){
	return  strings.Split(value,",")
}

/**
	字符串转化int
 */
 func GetInt(value string,defaultvalue int) (v int){
	 result,err := strconv.Atoi(value)
	 if err != nil {
	 	log.Error(err)
	 	return defaultvalue
	 }
	 return result
 }

 /**
 	将String 类型转化为Bool类型
  */
func ToBool(value string,defaultvalue bool) (v bool){
	result,err := strconv.ParseBool(value)
	if err!= nil {
		log.Error(err)
		return defaultvalue
	}
	return result
}
/**
	字符串反转
 */
func ReverseStr(src string) string {
	dst := []rune(src)
	var result []rune

	result = make([]rune, 0)
	for i := len(dst) - 1; i >= 0; i-- {
		result = append(result, dst[i])
	}
	return string(result)
}

/**
	如果字符串的长度不够，就在其左侧位补零
 */
func SpaceStr(src string,length int) string {
	if len(src)>=length{
		return src
	}
	format := "%"+fmt.Sprintf("%s%v","0",length)+"s"
	return fmt.Sprintf(format,src)
}

